package com.biz.primus.model.member.exception;

import com.fasterxml.classmate.TypeResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.TypeNameExtractor;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;

import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.newHashSet;

/**
 * Created by liangbin on 2017/11/29.
 */
public class UserExceptionResponseReader implements OperationBuilderPlugin {

    @Override
    public void apply(OperationContext context) {
        context.operationBuilder()
                .responseMessages(read(context));
    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        return DocumentationType.SWAGGER_2==documentationType;
    }

    protected Set<ResponseMessage> read(OperationContext context) {

        List<UserExceptionResponse> allApiResponses = context.findAllAnnotations(UserExceptionResponse.class);
        Set<ResponseMessage> responseMessages = newHashSet();

        Map<Integer, UserExceptionType> seenResponsesByCode = newHashMap();
        for (UserExceptionResponse userExceptionResponse : allApiResponses) {
            UserExceptionType[] apiResponseAnnotations = userExceptionResponse.value();
            for (UserExceptionType userExceptionType : apiResponseAnnotations) {
                if (!seenResponsesByCode.containsKey(userExceptionType.getCode())) {
                    seenResponsesByCode.put(userExceptionType.getCode(), userExceptionType);
                    responseMessages.add(new ResponseMessageBuilder()
                            .code(userExceptionType.getCode())
                            .message(userExceptionType.getDescription())
                            .build());
                }
            }
        }

        return responseMessages;
    }

}
